﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using DMS.Base;
using DMS.BaseClass;
using DMS.Business.Modules.SupplierManagement;
using DMS.Business.Utility;
using DMS.Business.Modules.Organization;
using System.Web.UI.HtmlControls;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.IO;
using System.Web;
using System.Data;

namespace DMS.Web.Common.Controls
{
    public partial class RoleMemberListCtrl : ListControlBase
    {
        #region 成员属性
        /// <summary>
        /// 当前角色ID
        /// </summary>
        public string ContextRoleID
        {
            get
            {
                return this.hidRoleID.Value;
            }
            set
            {
                this.hidRoleID.Value = value;
            }
        }
        public string ConbtextRoleName
        {
            get
            {
                return this.hidRoleName.Value;
            }
        }
        /// <summary>
        /// 页大小限制
        /// </summary>
        public int PageLimte
        {
            get
            {
                return this.pager.PageSize;
            }
            set
            {
                this.pager.PageSize = value;
            }
        }
        private string _OnClientSelectBtnClick = string.Empty;
        public string OnClientSelectBtnClick
        {
            get
            {
                return this._OnClientSelectBtnClick;
            }
            set
            {
                this._OnClientSelectBtnClick = value;
            }
        }
        protected override List<Control> ControlSet
        {
            get
            {
                List<Control> ctrls = new List<Control>();
                //ctrls.Add(this.imgAdd);

                return ctrls;
            }
        }
        protected override List<string> ControlSetInGrid
        {
            get
            {
                List<string> ctrlIds = new List<string>();

                return ctrlIds;
            }
        }
        protected override Dictionary<int, string> ColumnStateSettings
        {
            get
            {
                Dictionary<int, string> settings = new Dictionary<int, string>();
                foreach (ListItem item in this.lbGridColState.Items)
                {
                    try
                    {
                        int key = Convert.ToInt32(item.Text);
                        string value = item.Value;
                        settings.Add(key, value);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogException(ex);
                    }
                }

                return settings;
            }
        }
        protected override WebControl MainListControl
        {
            get
            {
                return this.dgRoleList;
            }
        }
        #endregion

        #region 界面事件
        /// <summary>
        /// 控件加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.GetParams();

            if (!IsPostBack && !string.IsNullOrEmpty(this.ContextRoleID))
            {
                this.InitDataList();
            }
        }
        /// <summary>
        /// 数据绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void dgRoleList_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
            {
                return;
            }

            Actor actor = e.Item.DataItem as Actor;
            if (actor == null)
            {
                return;
            }

            Label lblActorType = e.Item.FindControl("lblActorType") as Label;
            Label lblFullName = e.Item.FindControl("lblFullName") as Label;
            Literal ltlFullName = e.Item.FindControl("ltlFullName") as Literal;
            if (lblActorType != null && lblFullName != null && ltlFullName != null)
            {
                switch (actor.ActorType)
                {
                    case ActorTypes.User:
                        lblActorType.Text = "内部用户";
                        User user = UserHelper.GetUserByID(actor.ID);
                        lblFullName.Text = Server.HtmlEncode(user.Dept.Name);
                        ltlFullName.Text = Server.HtmlEncode(user.Dept.FullName);
                        break;
                    case ActorTypes.Dept:
                        lblActorType.Text = "部门";
                        Department dept = UserHelper.GetDepartmentByID(actor.ID);
                        lblFullName.Text = Server.HtmlEncode(dept.Name);
                        ltlFullName.Text = Server.HtmlEncode(dept.FullName);
                        break;
                    case ActorTypes.Supplier:
                        lblActorType.Text = "供应商";
                        Supplier supplier = SupplierHelper.GetSupplierByID(actor.ID);
                        lblFullName.Text = supplier.Name;
                        ltlFullName.Text = lblFullName.Text;
                        break;
                    case ActorTypes.SupplierAccount:
                        lblActorType.Text = "供应商用户";
                        SupplierAccount account = SupplierHelper.GetAccountByID(actor.ID);
                        lblFullName.Text = account.Company.Name;
                        ltlFullName.Text = lblFullName.Text;
                        break;
                    case ActorTypes.Role:
                        lblActorType.Text = "成员角色";
                        Role role = UserHelper.GetRoleByID(actor.ID);
                        lblFullName.Text = role.Name;
                        ltlFullName.Text = lblFullName.Text;
                        break;
                }
            }

            Label lblScope = e.Item.FindControl("lblScope") as Label;
            HiddenField hidScope = e.Item.FindControl("hidScope") as HiddenField;
            if (lblScope != null && hidScope != null)
            {
                if (string.IsNullOrEmpty(actor.MemberScope))
                {
                    lblScope.Text = "全局角色";
                    lblScope.ToolTip = lblScope.Text;
                    hidScope.Value = actor.MemberScope;
                }
                else
                {
                    lblScope.Text = UserHelper.GetDeptNameByID(actor.MemberScope);
                    lblScope.ToolTip = lblScope.Text;
                    hidScope.Value = actor.MemberScope;
                }
            }

            Literal ltlLoginID = e.Item.FindControl("ltlLoginID") as Literal;
            if (ltlLoginID != null && actor is AuthenticationUser)
            {
                ltlLoginID.Text = string.Format("({0})", ((AuthenticationUser)actor).LoginID);
            }

            //LinkButton lbtnSetScope = e.Item.FindControl("lbtnSetScope") as LinkButton;
            //if (lbtnSetScope != null && hidScope != null)
            //{
            //    lbtnSetScope.CommandArgument = string.Format("{0}#{1}", actor.ID.ToString(), actor.ActorType.ToString());
            //    lbtnSetScope.OnClientClick = string.Format("return GetScopes(this, '{0}');", hidScope.ClientID);
            //}

            LinkButton lbtnDelete = e.Item.FindControl("lbtnDelete") as LinkButton;
            if (lbtnDelete != null)
            {
                lbtnDelete.CommandArgument = string.Format("{0}#{1}", actor.ID.ToString(), actor.ActorType.ToString());
                lbtnDelete.OnClientClick = string.Format("javascrpt:return confirm('确认要从“{0}”删除“{1}”？')", this.ConbtextRoleName, actor.Name);
            }

            Literal ltlNameRemark = e.Item.FindControl("ltlNameRemark") as Literal;
            if (ltlNameRemark != null && actor.ActorType == ActorTypes.User)
            {
                User user = actor as User;
                ltlNameRemark.Text = string.Format("（{0}）", user.Dept.FullName);
            }

            HtmlAnchor lkSelectBtn = e.Item.FindControl("lkSelectBtn") as HtmlAnchor;
            if (lkSelectBtn != null && !string.IsNullOrEmpty(this._OnClientSelectBtnClick))
            {
                string script = this._OnClientSelectBtnClick;
                if (actor.ActorType == ActorTypes.User)
                {
                    User user = actor as User;
                    if (this._OnClientSelectBtnClick.Contains("%ActorType%"))
                    {
                        script = script.Replace("%ActorType%", user.ActorType.ToString());
                    }
                    if (this._OnClientSelectBtnClick.Contains("%ID%"))
                    {
                        script = script.Replace("%ID%", user.ID.ToString());
                    }
                    if (this._OnClientSelectBtnClick.Contains("%Name%"))
                    {
                        script = script.Replace("%Name%", user.Name);
                    }
                    if (this._OnClientSelectBtnClick.Contains("%LoginID%"))
                    {
                        script = script.Replace("%LoginID%", user.LoginID);
                    }
                    if (this._OnClientSelectBtnClick.Contains("%DeptFullName%") && user.Dept != null)
                    {
                        script = script.Replace("%DeptFullName%", user.Dept.FullName);
                    }
                    lkSelectBtn.Attributes["onclick"] = string.Format("javascript:{0};", script);
                }
            }
        }
        protected void dgRoleList_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                Guid roleID = new Guid(this.ContextRoleID);
                string[] args = e.CommandArgument.ToString().Split("#".ToCharArray());
                Guid actorID = new Guid(args[0]);
                ActorTypes actorType = (ActorTypes)Enum.Parse(typeof(ActorTypes), args[1]);

                if (e.CommandName == "Delete")
                {
                    UserHelper.DeleteUserRole(actorID, roleID);
                }
                else if (e.CommandName == "SetScope")
                {
                    string sql = @"UPDATE [dbo].[ORG_RoleMembers]
                                       SET [Scope] = '{2}'
                                     WHERE [RoleID] = '{0}'
                                       AND [MemberID] = '{1}'";
                    string query = string.Format(sql, roleID.ToString()
                                                    , actorID.ToString()
                                                    , this.hidCmdScope.Value);
                    Database db = DBHelper.Instance;
                    DbCommand cmd = db.GetSqlStringCommand(query);

                    try
                    {
                        db.ExecuteNonQuery(cmd);
                    }
                    catch (Exception ex)
                    {
                        string code = LogHelper.LogException(ex);
                        ClientHelper.Instance.Alert(string.Format("保存失败，请联系管理员。\\r\\n错误码：{0}", code));
                    }
                }

                this.InitDataList();
            }
            catch (Exception ex)
            {
                LogHelper.LogException(ex);
            }
        }
        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void pager_PageChanged(object sender, EventArgs e)
        {
            this.InitDataList();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            this.pager.GoToPage(1);
            this.InitDataList();
        }
        /// <summary>
        /// 添加新成员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtnAddMember_Click(object sender, EventArgs e)
        {
            try
            {
                //string memberIDs = this.hidNewMemberIDs.Value.Trim().Trim(";".ToCharArray());
                //string memberTypes = this.hidNewMemberTypes.Value.Trim().Trim(";".ToCharArray());

                //Guid roleID = new Guid(this.hidRoleID.Value);
                //Role role = UserHelper.GetRoleByID(roleID);

                //if (!string.IsNullOrEmpty(memberIDs)
                //    && !string.IsNullOrEmpty(memberTypes)
                //    && role != null)
                //{
                //    string[] memberIDArray = memberIDs.Split(";".ToCharArray());
                //    string[] memberTypeArray = memberTypes.Split(";".ToCharArray());
                //    for (int index = 0; index < memberIDArray.Length && index < memberTypeArray.Length; index++)
                //    {
                //        Guid actorID = new Guid(memberIDArray[index]);
                //        ActorTypes actorType = (ActorTypes)Enum.Parse(typeof(ActorTypes), memberTypeArray[index]);

                //        List<Role> roles = UserHelper.GetActorRole(actorID);
                //        if (!roles.Contains(role))
                //        {
                //            roles.Add(role);
                //        }

                //        List<string> targetRoles = (from r in roles
                //                                    select r.ID.ToString()).ToList<string>();
                //        UserHelper.SetActorRole(actorID, actorType, targetRoles.ToArray());
                //    }
                //}

                //ClientHelper.Instance.Alert("添加成功！");
                ClientHelper.Instance.RefreshPage(true);
            }
            catch (Exception ex)
            {
                string code = LogHelper.LogException(ex);
                string msg = string.Format("添加角色成员时出错，请联系管理员\\r\\n错误码：{0}", code);
                ClientHelper.Instance.Alert(msg);
            }
            ClientHelper.Instance.RefreshPage(true);
        }

        protected void lbtnExport_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("名称");
            dt.Columns.Add("所在部门");
            dt.Columns.Add("管理范围");

            List<Actor> members = GetData();
            foreach (Actor actor in members)
            {
                User user = actor as User;
                if (user != null)
                {
                    string memberScope = UserHelper.GetDeptNameByID(actor.MemberScope);

                    dt.Rows.Add(user.Name, user.Dept.Name, memberScope);
                }
            }
            
            ClientHelper.Instance.ExportToExcel(dt, "members");
        }
        #endregion

        #region 内部方法
        /// <summary>
        /// 获取参数
        /// </summary>
        private void GetParams()
        {
            // 角色ID
            if (!string.IsNullOrEmpty(Request["RoleID"]))
            {
                this.ContextRoleID = this.Request["RoleID"].ToString().ToUpper();
            }
            if (!string.IsNullOrEmpty(Request["Title"]))
            {
                this.lblItemTitle.Text = this.Request["Title"].ToString();
            }
        }

        private List<Actor> GetData()
        {
            List<Actor> members = new List<Actor>();

            if (!string.IsNullOrEmpty(this.ContextRoleID))
            {
                Role role = UserHelper.GetRoleByID(ContextRoleID);
                if (role != null)
                {
                    this.hidRoleName.Value = role.Name;
                }

                string condition = "";
                if (!string.IsNullOrEmpty(this.DeptName.Text.Trim()))
                {
                    condition = string.Format(" and od.DeptFullName like '%{0}%'", this.DeptName.Text.Trim());
                }

                members = UserHelper.GetRoleMembersWithCondition(role, condition);
                if (!string.IsNullOrEmpty(this.ddlActorType.SelectedValue))
                {
                    ActorTypes actorType = (ActorTypes)Enum.Parse(typeof(ActorTypes), this.ddlActorType.SelectedValue);
                    members = (from m in members
                               where m.ActorType == actorType
                               select m).ToList<Actor>();
                }
                if (!string.IsNullOrEmpty(this.txtActorName.Text.Trim()))
                {
                    members = (from m in members
                               where m.Name.Contains(this.txtActorName.Text.Trim())
                               select m).ToList<Actor>();
                }
            }

            return members;
        }

        /// <summary>
        /// 初始化列表
        /// </summary>
        public void InitDataList()
        {
            int total = 0;
            if (!string.IsNullOrEmpty(this.ContextRoleID))
            {
                List<Actor> members = GetData();
               
                List<Actor> memberToBind = new List<Actor>();
                int startIndex = 0;
                int endIndex = this.pager.PageSize-1;
                if (this.pager.CurrentPageIndex > 1)
                {
                    startIndex = (this.pager.CurrentPageIndex - 1) * this.pager.PageSize;
                    endIndex = startIndex + this.pager.PageSize-1;
                }
                for (int index = startIndex; index <= endIndex && index < members.Count; index++)
                {
                    memberToBind.Add(members[index]);
                }
                this.dgRoleList.DataSource = memberToBind;
                this.dgRoleList.DataBind();

                total = members.Count;
                this.pager.RecordCount = total;
            }

            // 处理空数据
            if (total == 0)
            {
                this.dgRoleList.Visible = false;
                this.pager.Visible = false;
                this.dvEmpty.Visible = true;
            }
            else
            {
                this.dgRoleList.Visible = true;
                this.pager.Visible = true;
                this.dvEmpty.Visible = false;
            }
        }
        #endregion
    }
}